package com.ndp.fb.walle.filters;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.rdb.api.FbUserRdbService;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.walle.model.vo.RespModel;
import com.ndp.fb.walle.util.ResponseUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by mikey.zhaopeng on 2015/7/6.
 * 检查accesstoken是否失效
 */
public class TokenValidateClientFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(getClass());
    private  String [] ignoreUrls={"login","sysmonitor","user","websocket","common","entrustaccounts","fboauth","logusers","organization"};

    @Reference
    private FbUserRdbService fbUserRdbService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        try {

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            log.info(httpServletRequest.getRequestURI());
            String[] requestURI = httpServletRequest.getRequestURI().split("/");
            if(requestURI.length>1){
                String filterUrl = requestURI[1];
                for (String ignoreUrl : ignoreUrls) {
                    if(ignoreUrl.equalsIgnoreCase(filterUrl)){
                        if(requestURI.length>2&&"entrustaccounts".equals(requestURI[1]) && "changeAccountList".equals(requestURI[2])){
                            log.info(httpServletRequest.getRequestURI());
                            break;
                        }else{
                            chain.doFilter(request, response);
                            return;
                        }
                    }
                }
            }else{
                chain.doFilter(request, response);
                return;
            }

            String userId = null;
            try {
                User user = (User) httpServletRequest.getSession().getAttribute("user");
                if(user!=null){
                    userId = user.getTicket();
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            if (StringUtils.isEmpty(userId)) {
                chain.doFilter(request, response);
                return;
            }
            boolean isInvaid = false;
            try {
                isInvaid = fbUserRdbService.getIsInvalidByUserId(userId);
            } catch (Exception e) {
                isInvaid = false;
            }
            if (isInvaid) {
                doFail(httpServletResponse, ErrorType.ACCESS_TOKEN_EXPIRE);
            } else {
                chain.doFilter(request, response);
            }
        }catch (Exception e1){
            log.error(e1.getMessage(), e1);
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }


    private void doFail(HttpServletResponse response, ErrorType errorType) throws ServletException, IOException {
        RespModel result = new RespModel();
        result.setFlag("fail");
        result.setMsg(ResponseUtils.getMsg(errorType));
        result.setErrorCode(errorType.getCode().toString());
        response.addHeader("Content-Type", "application/json; charset=utf-8");
        response.getWriter().print(JSON.toJSONString(result));
    }
}
